package com.trgzs.bate.common.exception;

import com.trgzs.bate.common.response.BaseResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author dongl
 * @date 2019/11/9
 * @PS 全局异常接收类
 */
@RestControllerAdvice
@Slf4j
@Order(-100)
public class GlobalExceptionHandler {


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(GlobalException.class)
    public BaseResult<Object> handleWarnException(HttpServletRequest request, GlobalException exception) {
        log.error("错误code: {}；错误信息: {}", exception.getCode(), exception.getMsg());
        return BaseResult.fail(exception.getCode(), exception.getMsg());
//        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ExceptionVO(exception.getCode(),exception.getMsg()) );
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public BaseResult<Object> Exception(HttpServletRequest request, Exception exception) {
        return BaseResult.fail(1000, exception.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(org.springframework.security.access.AccessDeniedException.class)
    public BaseResult<Object> accessDeniedException(HttpServletRequest request, Exception e) {

        return BaseResult.fail(1000, e.getMessage());
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public BaseResult<Object> runtimeException(HttpServletRequest request, Exception e) {

        return BaseResult.fail(1000, e.getMessage());
    }


//    /**
//     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
//     */
//    @ExceptionHandler(ConstraintViolationException.class)
//    public BaseResult<Object> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
//        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
//        return BaseResult.fail(GlobalExceptionEnum.CONSTRAINT_VIOLATION_ERROR.getCode(), message);
//    }

}
